package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DBTool {
	
	public DBTool(){
		
	}
	
	private static String dfurl="jdbc:mysql://localhost:3306/excel2table?useUnicode=true&characterEncoding=UTF-8";
	private static String dfusername="root";
	private static String dfpassword="root";
	private static Connection conn=null;
	
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (Exception ex) {
			System.out.println("驱动加载失败！");
			ex.printStackTrace();
		}
	}

	/**
	 * 得到某个数据库的连接
	 * @param url 不包含databaseName的url
	 * @param user 数据库用户
	 * @param pwd 密码
	 * @param dbName 数据库名
	 * */
	public Connection getCon(){
		try {
			conn=DriverManager.getConnection(dfurl, dfusername, dfpassword);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	public static Connection getCon(String url, String user, String pwd, String dbName) throws SQLException {
		conn = DriverManager.getConnection(url + "/" + dbName, user, pwd);
		System.out.println("url="+url+";databaseName="+dbName+";user="+user+";pwd="+pwd);
		return conn;
	}

	/**
	 * 关闭连接
	 * */
	public static void CloseCon(Connection con) {
		if (con != null) {
			try {
				con.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	/**
	 * 执行sql
	 * */
	public void execSql(String sql, Connection conn) throws Exception {
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.execute();
	}
	public void execSql(String sql) throws Exception {
		PreparedStatement ps = this.getCon().prepareStatement(sql);
		ps.execute();
	}
	/**
	 * 执行更新sql
	 * */
	public void execUpdate(String sql,Connection conn) throws Exception{
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.executeUpdate();
	}
	public void execUpdate(String sql) throws Exception{
		PreparedStatement ps = this.getCon().prepareStatement(sql);
		ps.executeUpdate();
	}
}
